require 'digest/sha2'
class User < ActiveRecord::Base
  USER_TYPES = ["librarian", "student", "admin"]
  validate :userid, :name, :date_of_birth,  :user_type, :email, :presence => true
  validates :userid, :uniqueness => true
  validates :email, :uniqueness => true
  
  validates :password, :confirmation => true
  attr_accessor :password_confirmation
  attr_reader   :password

  #validate  :password_must_be_present
  
  def User.admin_authenticate(userid, password)
    if user = find_by_userid(userid)
      if user.hashed_password == encrypt_password(password, user.salt) and user.user_type == 'admin'
        user
      end
    end
  end
  
  def User.librarian_authenticate(userid, password)
    if user = find_by_userid(userid)
      if user.hashed_password == encrypt_password(password, user.salt) and user.user_type == 'librarian'
        user
      end
    end
  end
  def User.student_authenticate(userid, password)
    if user = find_by_userid(userid)
      if user.hashed_password == encrypt_password(password, user.salt) and user.user_type == 'student'
        user
      end
    end
  end

  def User.encrypt_password(password, salt)
    Digest::SHA2.hexdigest(password + "wibble" + salt)
  end
  
  # 'password' is a virtual attribute
  def password=(password)
    @password = password

    if password.present?
      generate_salt
      self.hashed_password = self.class.encrypt_password(password, salt)
    end
  end
  
  private

    def password_must_be_present
      errors.add(:password, "Missing password") unless hashed_password.present?
    end
  
    def generate_salt
      self.salt = self.object_id.to_s + rand.to_s
    end
end
